package im

import (
	"context"
	"fmt"
	"server/component"
	"server/im/core"
	"server/im/gateway"
	"sync"
	"time"
)

var gatewayArr []gateway.GateWay
var coreHub *core.Hub

func Start() {
	var wg sync.WaitGroup

	//hub start
	coreHub = core.NewHub(context.Background())
	wg.Add(1)
	go coreHub.Start(&wg)

	//延迟2秒
	time.Sleep(time.Second * 2)

	//gateway start
	if len(component.ConfigModel.ImServers) > 0 {
		for _, imConfig := range component.ConfigModel.ImServers {
			imGateway := gateway.NewGateway(context.Background(), imConfig)
			gatewayArr = append(gatewayArr, imGateway)
			wg.Add(1)
			go imGateway.Start(&wg)
		}
	}
	wg.Wait()

	component.Log.Info("im stopped")
}

func Stop() {
	fmt.Println("im do stop")
	//关闭网关
	for _, g := range gatewayArr {
		g.Stop()
	}
	//延迟2秒
	time.Sleep(time.Second * 2)
	//关闭hub
	coreHub.Stop()
}
